﻿#region 命名空间

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using WinnerCMS.Common;
using WinnerCMS.Data;
using WinnerCMS.CacheStorager;
using WinnerCMS.Model;

#endregion

namespace WinnerCMS.BLL.PageFactory
{
    /// <summary>
    /// 得到并生成Html
    /// </summary>
    public class SaveHTML
    {
        private readonly byte _modelId;

        private static int _threadNum;
        private static ManualResetEvent _synchro;


        private IList<string> _urlList;

        public SaveHTML(byte modelId)
        {
            this._modelId = modelId;
            CMSConfig config = CMSConfig.Instance();
            _threadNum = config.ThreadNum;
        }

        #region 生成内容页

        /// <summary>
        /// 生成内容页
        /// </summary>
        /// <param name="top"></param>
        public void ContentPage(int top)
        {
            Thread th = new Thread(ContentPage_TOP);
            th.Start(top);
        }

        /// <summary>
        /// 生成内容页
        /// </summary>
        /// <param name="Top"></param>
        private void ContentPage_TOP(object Top)
        {
            CMSCaches.Context.Add("ContentPage_" + this._modelId + "_Message", "正在组织任务列队", 3600);

            this._urlList = new MakingUrlList().MakeContentPage(Convert.ToInt32(Top), this._modelId);

            CMSCaches.Context.Add("ContentPage_" + this._modelId + "_Message", "正在生成静态页", 3600);

            CMSCaches.Context.Add("ContentPage_" + this._modelId + "_Tatol", this._urlList.Count, 100);
            CMSCaches.Context.Add("ContentPage_" + this._modelId + "_Progress", 0, 100);
            for (int i = 0; i < this._urlList.Count; i++)
            {
                Thread th = new Thread(Save);

                if (_threadNum > 0)
                {
                    _threadNum--;

                    th.Start(i);

                    CMSCaches.Context.Add("ContentPage_" + this._modelId + "_Tatol", this._urlList.Count, 100);
                    CMSCaches.Context.Add("ContentPage_" + this._modelId + "_Progress", i + 1, 100);
                }
                else
                {
                    _synchro = new ManualResetEvent(false);
                    _synchro.WaitOne(); //等待   
                    _threadNum--;

                    th.Start(i);

                    CMSCaches.Context.Add("ContentPage_" + this._modelId + "_Tatol", this._urlList.Count, 100);
                    CMSCaches.Context.Add("ContentPage_" + this._modelId + "_Progress", i + 1, 100);
                }
            }

            Log logModel = new Log
            {
                Type = "内容发布",
                Event = string.Concat("生成“", ModelManage.GetModelName(this._modelId), "”内容页", this._urlList.Count,
                    "个"),
                UserName = "CMS_Robot"
            };
            LogManage.Add(logModel);
        }

        /// <summary>
        /// 生成内容页
        /// </summary>
        /// <param name="where"></param>
        public void ContentPage(object @where)
        {
            Thread th = new Thread(ContentPage_WHERE);
            th.Start(@where);
        }

        /// <summary>
        /// 生成内容页
        /// </summary>
        /// <param name="where"></param>
        private void ContentPage_WHERE(object @where)
        {
            CMSCaches.Context.Add("ContentPage_" + this._modelId + "_Message", "正在组织任务列队", 3600);

            if (@where is int[])
            {
                int[] ids = (int[]) @where;
                this._urlList = new MakingUrlList().MakeContentPage(ids[0], ids[1], this._modelId);
            }
            else if (@where is DateTime[])
            {
                DateTime[] times = (DateTime[]) @where;
                this._urlList = new MakingUrlList().MakeContentPage(times[0], times[1], this._modelId);
            }
            else
            {
                this._urlList = new MakingUrlList().MakeContentPage((int) @where, this._modelId);
            }

            CMSCaches.Context.Add("ContentPage_" + this._modelId + "_Message", "正在生成静态页", 3600);

            string tatolId = "ContentPage_" + this._modelId + "_Tatol";
            string progressId = "ContentPage_" + this._modelId + "_Progress";

            for (int i = 0; i < this._urlList.Count; i++)
            {
                Thread th = new Thread(Save);

                if (_threadNum > 0)
                {
                    _threadNum--;

                    th.Start(i);

                    CMSCaches.Context.Add(tatolId, this._urlList.Count, 500);
                    CMSCaches.Context.Add(progressId, i + 1, 500);
                }
                else
                {
                    _synchro = new ManualResetEvent(false);
                    _synchro.WaitOne(); //等待   
                    _threadNum--;

                    th.Start(i);

                    CMSCaches.Context.Add(tatolId, this._urlList.Count, 500);
                    CMSCaches.Context.Add(progressId, i + 1, 500);
                }
            }

            Log logModel = new Log();
            logModel.Type = "内容发布";
            logModel.Event = string.Concat("生成“", ModelManage.GetModelName(this._modelId), "”内容页", this._urlList.Count,
                "个");
            logModel.UserName = "CMS_Robot";
            LogManage.Add(logModel);
        }

        #endregion

        #region 栏目页

        /// <summary>
        /// 栏目页
        /// </summary>
        /// <param name="ids"></param>
        public void CategoryPage(string ids)
        {
            Thread th = new Thread(CategoryPage);
            th.Start(ids);
        }

        /// <summary>
        /// 栏目页
        /// </summary>
        /// <param name="ids"></param>
        private void CategoryPage(object ids)
        {
            CMSCaches.Context.Add("CategoryPage_" + this._modelId + "_Message", "正在组织任务列队", 3600);
            if (ids == null)
            {
                this._urlList = new MakingUrlList().MakeCategoryPage(this._modelId);
            }
            else
            {
                this._urlList = new MakingUrlList().MakeCategoryPage(ids.ToString(), this._modelId);
            }
            CMSCaches.Context.Add("CategoryPage_" + this._modelId + "_Message", "正在生成静态页", 3600);

            for (int i = 0; i < this._urlList.Count; i++)
            {
                Thread th = new Thread(Save);

                if (_threadNum > 0)
                {
                    _threadNum--;

                    th.Start(i);

                    CMSCaches.Context.Add("CategoryPage_" + this._modelId + "_Tatol", this._urlList.Count, 100);
                    CMSCaches.Context.Add("CategoryPage_" + this._modelId + "_Progress", i + 1, 100);
                }
                else
                {
                    _synchro = new ManualResetEvent(false);
                    _synchro.WaitOne(); //等待   
                    _threadNum--;

                    th.Start(i);

                    CMSCaches.Context.Add("CategoryPage_" + this._modelId + "_Tatol", this._urlList.Count, 100);
                    CMSCaches.Context.Add("CategoryPage_" + this._modelId + "_Progress", i + 1, 100);
                }
            }
            Log logModel = new Log();
            logModel.Type = "内容发布";
            logModel.Event = string.Concat("生成“", ModelManage.GetModelName(this._modelId), "”栏目页", this._urlList.Count,
                "个");
            logModel.UserName = "CMS_Robot";
            LogManage.Add(logModel);
        }

        #endregion

        #region 专题栏目

        public void SpecialPage(string @where)
        {
            Thread th = new Thread(SpecialPage);
            th.Start(@where);
        }

        private void SpecialPage(object @where)
        {
            CMSCaches.Context.Add("SpecialPage_" + this._modelId + "_Message", "正在组织任务列队", 3600);
            this._urlList = new MakingUrlList().MakeSpecialPage(@where.ToString(), this._modelId);
            CMSCaches.Context.Add("SpecialPage_" + this._modelId + "_Message", "正在生成静态页", 3600);
            for (int i = 0; i < this._urlList.Count; i++)
            {
                Thread th = new Thread(Save);
                //th.Start(i);
                //th.Join();

                if (_threadNum > 0)
                {
                    _threadNum--;

                    th.Start(i);

                    CMSCaches.Context.Add("SpecialPage_" + this._modelId + "_Tatol", this._urlList.Count, 100);
                    CMSCaches.Context.Add("SpecialPage_" + this._modelId + "_Progress", i + 1, 100);
                }
                else
                {
                    _synchro = new ManualResetEvent(false);
                    _synchro.WaitOne(); //等待   
                    _threadNum--;

                    th.Start(i);

                    CMSCaches.Context.Add("SpecialPage_" + this._modelId + "_Tatol", this._urlList.Count, 100);
                    CMSCaches.Context.Add("SpecialPage_" + this._modelId + "_Progress", i + 1, 100);
                }
            }

            Log logModel = new Log();
            logModel.Type = "内容发布";
            logModel.Event = string.Concat("生成“", ModelManage.GetModelName(this._modelId), "”专题页", this._urlList.Count,
                "个");
            logModel.UserName = "CMS_Robot";
            LogManage.Add(logModel);
        }

        #endregion

        /// <summary>
        /// 首页
        /// </summary>
        public void IndexPage()
        {
            string url = new MakingUrlList().IndexPage();
            GetWebCode(url);

            Log logModel = new Log();
            logModel.Type = "内容发布";
            logModel.Event = "生成首页";
            logModel.UserName = "CMS_Robot";
            LogManage.Add(logModel);
        }

        /// <summary>
        /// 模型的所有网页
        /// </summary>
        /// <param name="modelId"></param>
        public void ALL(string modelId)
        {
            Thread th = new Thread(ALL);
            th.Start(modelId);
        }

        /// <summary>
        /// 模型的所有网页
        /// </summary>
        /// <param name="modelId"></param>
        public void ALL(object modelId)
        {
            CMSCaches.Context.Add("MakeAll_" + this._modelId + "_Message", "正在组织任务列队", 3600);
            this._urlList = new MakingUrlList().All(Convert.ToByte(modelId));
            CMSCaches.Context.Add("MakeAll_" + this._modelId + "_Message", "正在生成静态页", 3600);

            for (int i = 0; i < this._urlList.Count; i++)
            {
                Thread th = new Thread(Save);
                if (_threadNum > 0)
                {
                    _threadNum--;

                    th.Start(i);

                    CMSCaches.Context.Add("MakeAll_" + this._modelId + "_Tatol", this._urlList.Count, 100);
                    CMSCaches.Context.Add("MakeAll_" + this._modelId + "_Progress", i + 1, 100);
                }
                else
                {
                    _synchro = new ManualResetEvent(false);
                    _synchro.WaitOne(); //等待   
                    _threadNum--;

                    th.Start(i);

                    CMSCaches.Context.Add("MakeAll_" + this._modelId + "_Tatol", this._urlList.Count, 100);
                    CMSCaches.Context.Add("MakeAll_" + this._modelId + "_Progress", i + 1, 100);
                }
            }

            Log logModel = new Log();
            logModel.Type = "内容发布";
            logModel.Event = string.Concat("生成“", ModelManage.GetModelName(this._modelId), "”所有页面");
            logModel.UserName = "CMS_Robot";
            LogManage.Add(logModel);
        }


        /// <summary>
        /// 保存html
        /// </summary>
        /// <param name="index"></param>
        private void Save(object index)
        {
            if (index == null)
            {
                throw new ArgumentNullException("输入参数错误.");
            }

            int _index = Convert.ToInt32(index);

            //System.Threading.Thread.Sleep(Config.ThreadSleepTime);


            GetWebCode(this._urlList[_index]);


            _threadNum++;
            if (_threadNum > 0)
            {
                if (_synchro != null)
                    _synchro.Set(); //激活等待
            }
        }

        #region 取得网页源代码

        /// <summary>
        /// 取得网页源代码
        /// </summary>
        /// <param name="strUrl">要取的URL</param>
        /// <returns>网页源代码</returns>
        internal static void GetWebCode(string strUrl)
        {
            strUrl = strUrl.Replace(@"\", "/");
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(strUrl);
            request.Proxy = null;
            request.ProtocolVersion = HttpVersion.Version11;
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout = 60*1000; //60秒钟
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";

            WebResponse wr = request.GetResponse();
            wr.Close();
        }

        #endregion
    }
}